#coding:utf-8

import itchat
import threading
import time

class WeBot(object):
    def __init__(self):
        super(WeBot).__init__()


    def test(self):
        itchat.auto_login()
        fri = itchat.search_friends(nickName= 'CL良辰' )[0]
        print(fri)
        itchat.send('老婆', toUserName=fri['UserName'])
        itchat.run()

    @itchat.msg_register(itchat.content.TEXT)
    def text_reply(msg):
        print(msg)
        return ''

    def start_bot(self):
        itchat.auto_login()
        # itchat.run()
        threading.Thread(target=self._heart_beat).start()
        threading.Thread(target=itchat.run).start()

    def _heart_beat(self):
        """
        心跳包，防止账号失效
        :return: 
        """
        user = itchat.search_friends(remarkName='WECHAT')
        if len(user) == 0:
            # print('指定用户不存在，无法发送消息')
            return
        else:
            user = user[0]
        while True:
            # 每5分钟发送一条心跳
            itchat.send_msg('Heart Beat', user['UserName'])
            time.sleep(1800)

    def send_msg(self, msg, remarkName=None):
        """
        发送消息
        :param nickNames: 
        :return: 
        """
        # 查找指定备注名的用户，并向其发送指定消息
        user = itchat.search_friends(name=remarkName)
        if len(user) == 0:
            print('抱歉，无法找到对应的用户，所以消息并未发送: %s'%(remarkName))
            return -1
        else:
            user = user[0]
            itchat.send_msg(msg, user['UserName'])


if __name__ == '__main__':
    wb = WeBot()
    wb.start_bot()
    while True:
        wb.send_msg('Hello你好',remarkName='文')
        time.sleep(2)
